import React, { useCallback, useEffect, useState } from 'react'
import { List, Cate, Lecturer, Update,DeleteOne,DeleteMany } from '../../axiosAPI/lzh'
import { Table, Link, Popconfirm, Tag, Select, Button, Input, MessagePlugin } from 'tdesign-react';
import { CheckCircleFilledIcon, CloseCircleFilledIcon, AddIcon, SearchIcon, DeleteIcon } from 'tdesign-icons-react';
import { useNavigate } from 'react-router-dom';
import moment from 'moment';
import '../../scss/lzh.scss'

const ExamList = () => {
  // const Now = useMemo(()=>{
  //   return Date.now()
  // },[])
  const columns = [
    {
      colKey: 'row-select',
      type: 'multiple',
      width: 46,
      fixed: 'left',
    },
    {
      colKey: 'name',
      title: '试卷名称',
      align: 'center',
      width: 280,
      fixed: 'left',
    },
    {
      colKey: 'type',
      title: '题目抽取',
      width: 110,
      align: 'center',
      cell: (item) => {
        let status = item.row.type;
        return (<Tag
          shape="round"
          theme={typeNameListMap[status].theme}
          variant="light-outline"
          icon={typeNameListMap[status].icon}>
          {typeNameListMap[status].label}</Tag>);
      },
    },
    {
      colKey: 'belong.name',
      title: '试卷分类',
      width: 120,
      align: 'center',
    },
    {
      colKey: 'status',
      title: '状态',
      align: 'center',
      cell: (item) => {
        let now = Date.now();
        if (now < item.row.time[0]) {
          return <div>未开始</div>
        } else if (now > item.row.time[1]) {
          return <div>已结束</div>
        } else {
          return <div>进行中</div>
        }
      },
    },
    {
      colKey: 'time',
      title: '考试时间',
      align: 'center',
      width: 330,
      cell: (item) => {
        let arr = item.row.time.map(item => {
          return moment(item).format('YYYY-MM-DD HH:mm:ss');
        })
        return <div>{arr[0]} - {arr[1]}</div>
      },
    },
    {
      colKey: 'publishTime',
      title: '提交日期',
      align: 'center',
      width: 200
    },
    {
      colKey: 'creator.name',
      title: '创建人',
      align: 'center',
    },
    {
      colKey: 'flag',
      title: '审核状态',
      align: 'center',
      width: 110,
      cell: (item) => {
        let status = item.row.flag;
        if (status === 1) {
          return <div>待审核</div>
        } else if (status === 2) {
          return <div>已发布</div>
        } else {
          return <div>已驳回</div>
        }
      },
    },
    {
      colKey: 'questions.length',
      title: '试题数量',
      align: 'center',
      width: 90,
    },
    {
      colKey: 'operate',
      align: 'center',
      width: 200,
      title: '操作',
      fixed: 'right',
      cell: ({ row }) => (
        <div className="tdesign-table-demo__table-operations" id='chkforselect'>
          {<Link
            hover="color"
            onClick={() => navigate(`/home/examAdd/topic?_id=${row._id}`)}>详情
          </Link>}
          {(row.flag === 2 && row.time[1] < Date.now())
            &&
            <Link
              hover="color"
              onClick={() => { navigate() }}>统计
            </Link>}
          {row.flag === 1 && <Link hover="color" onClick={() => update(row._id, 3)}>驳回</Link>}
          {row.flag === 1 && <Link
          hover="color"
            onClick={() => update(row._id, 2)}>发布</Link>}
          <Popconfirm content="确认删除吗" onConfirm={() => onDeleteConfirm(row._id)}>
            <Link
            disabled={row.flag === 2}
              hover="color">删除</Link>
          </Popconfirm>
        </div>),
    },
  ];
  const typeNameListMap = {
    false: {
      label: '随机抽取',
      theme: 'success',
      icon: <CheckCircleFilledIcon />,
    },
    true: {
      label: '固定选择',
      theme: 'danger',
      icon: <CloseCircleFilledIcon />,
    },
  }
  const navigate = useNavigate()
  const [list, setlist] = useState([])
  const [load, setload] = useState(true)
  const [page, setpage] = useState(1)
  const [pagesize, setpagesize] = useState(4)
  const [total, setTotal] = useState(0)
  const [options, setOptions] = useState([])
  const [str, setstr] = useState('')
  const [cate, setcate] = useState('')
  const [state, setstate] = useState(0)
  const [lecturers, setlecturers] = useState([])
  const [curlecturer, setcurlecturer] = useState('')
  const [paperTotal,setPaperTotal] = useState(0)
  // const [daterange, setdaterange] = useState([])
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  useEffect(() => {
    getcate();
    lecturer();
  }, [])
  useEffect(()=>{
    getlist();
  },[page,pagesize,cate,state,curlecturer,str])

  const getlist = useCallback(async () => {
    setload(true)
    const { data: { data, code,total } } = await List({
      page:page,
      cate:cate,
      flag: state,
      creator: curlecturer,
      str:str,
      pagesize:pagesize
    });
    setTotal(total)
    data.forEach(item => {
      item.publishTime = moment(item.publishTime).format('YYYY-MM-DD HH:mm:ss')
    });
    if (code === 200) {
      setload(false)
      setlist(data)
    }
  },[page,pagesize,cate,state,curlecturer,str])
  const getcate = async () => {
    const { data: { code, data } } = await Cate();
    if (code === 200) {
      let arr = data.map(item => {
        return {
          label: item.name,
          value: item._id
        }
      })
      setOptions(arr)
    }
  }
  const lecturer = async () => {
    const { data: { code, data } } = await Lecturer();
    if (code === 200) {
      let arr = data.map(item => {
        return {
          label: item.name,
          value: item._id
        }
      })
      setlecturers(arr)
    }
  }
  const chgstr = (v) => {
    setstr(v)
  }
  const update = async (_id, flag) => {
    const { data: { code, msg } } = await Update({ _id, flag })
    if (code === 200) {
      MessagePlugin.success(msg)
      getlist()
    } else {
      MessagePlugin.error(msg)
    }
  }
  const onChange = (value) => {
    setcate(value);
  };
  const onChange2 = (value) => {
    setstate(value);
  };
  const onChange3 = (value) => {
    setcurlecturer(value);
  }
  // const onPick = (value, context) => {
  //   const timestamp = new Date(value).getTime();
  //   setdaterange(arr => arr.concat(timestamp))
  // };
  // const onChangeDateRange = (value, { dayjsValue }) => {
  //   console.log(value);
  // }
  const clear = () => {
    setstr('');
    setcate('');
    setstate('');
    setcurlecturer('');
  }
  const rehandleChange = async (pageInfo)=> {
    const { current, pageSize } = pageInfo;
    setpage(current);
    setpagesize(pageSize);
  }
  const onSelectChange = (value, { selectedRowData }) => {
    setSelectedRowKeys(value);
    console.log(value, selectedRowData);
  };
  const onDeleteConfirm = async(_id)=>{
    const {data:{code}} = await DeleteOne({_id})
    if(code===200){
      MessagePlugin.success('删除成功')
      getlist()
    }else{
      MessagePlugin.error('删除失败')
    }
  }

  return (
    <div id='examList'>

      <div className='l1'>
        <div className="bbb">
          <div className="i">试卷名称：</div>
          <Input placeholder="请输入试卷名称" value={str} onChange={(e) => chgstr(e)} style={{ width: '60%' }} />
        </div>
        <div className='bbb'>
          <div className='i'>试卷分类：</div>
          <Select
            value={cate}
            onChange={onChange}
            style={{ width: '60%' }}
            clearable
            options={options}
          /></div>
        <div className="bbb">
          <div className="i">状态：</div>
          <Select
            value={state}
            onChange={onChange2}
            style={{ width: '60%' }}
            clearable
            options={[{ label: '待审核', value: 1 }, { label: '已发布', value: 2 }, { label: '已驳回', value: 3 }, { label: '进行中', value: 4 }, { label: '已结束', value: 5 }, { label: '未开始', value: 6 }]}
          />
        </div>
        <div className="bbb">
          <div className="i">创建人：</div>
          <Select
            value={curlecturer}
            onChange={onChange3}
            style={{ width: '60%' }}
            clearable
            options={lecturers}
          />
        </div>
        <Button icon={<DeleteIcon />} theme='danger' onClick={clear}>清空筛选</Button>

      </div>

      <div className="btn">
      <Button icon={<AddIcon />}
        style={{ marginLeft: '45px' }}
        onClick={() => navigate('/home/examAdd/topic')}>新增考试</Button>
        <Button theme='danger' style={{marginLeft:'45px'}} onClick={()=>DeleteMany({ids:selectedRowKeys})}>批量删除</Button>
      </div>
      <Table
        data={list}
        pagination={{
          current:page,
          pageSize:pagesize,
          total,
          defaultPageSize:pagesize,
          pageSizeOptions:[4,8,10,12],
          showJumper: true,
          onChange(pageInfo) {
            rehandleChange(pageInfo);
          },
        }}
        onSelectChange={onSelectChange}
        columns={columns} rowKey="_id"
        loading={load}
        hover={true}
      ></Table>
    </div>
  )
}

export default ExamList
